<template>
  <div class="app-container">
    <el-input style="width: 250px;" v-model="queryParams.goodsName" placeholder="商品名称"></el-input>
    <el-input style="width: 250px; margin-left: 20px;" v-model="queryParams.goodsContent"  placeholder="内容"></el-input>

    <el-dropdown style="margin-left: 20px;">
      <el-select v-model="value" placeholder="商品状态">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
      </el-select>
    </el-dropdown>

    <el-date-picker
      style="margin-left: 20px;"
      v-model="startTime"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期">
    </el-date-picker>

    <el-button style="margin-left: 20px;" @click="handleQuery" type="primary" icon="el-icon-search">搜索</el-button>
    <el-button style="margin-left: 20px;" @click="handleReset" type="info" icon="el-icon-refresh-left">重置</el-button>
    <el-button style="margin-left: 20px;" type="success"  icon="el-icon-bottom">导出</el-button>
    <br></br>
    <el-button  @click="dialogVisible=true" type="warning" round icon="el-icon-circle-plus-outline">新增</el-button>
    
    
    <!-- 对话框 -->
    <el-dialog title="添加商品"  :visible.sync="dialogVisible" width="50%">
      <!-- 表单 -->
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="销售语言：" prop="goodsName">
          <template>
            <el-select v-model="formData.langvage" placeholder="请选择">
              <el-option
                v-for="item in langvageList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="商品名称：" prop="goodsName">
          <el-input v-model="formData.goodsName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="商品主标题：" prop="mainTitle">
          <el-input v-model="formData.mainTitle" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="商品副标题：" prop="coTitle">
          <el-input v-model="formData.coTitle" placeholder="请输入"></el-input>
        </el-form-item>

        <el-form-item label="主图：" prop="mainImg">
          <el-upload
            class="upload-demo"
            action="#"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-fail="handleError"
            :file-list="fileList"
            :http-request="handleUpload"
            :auto-upload="false"
            list-type="picture-card">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip" style="display: inline-block; margin-left: 15px;vertical-align: middle;">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品内容：" prop="goodsContent">
          <template>
            <div>
              <quill-editor
                v-model="formData.goodsContent"
                :options="editorOption"
                style="height: 200px;"
              />
            </div>
          </template>
        </el-form-item>
        <el-form-item label="购买地址：" style="margin-top: 80px;" prop="link">
          <el-input v-model="formData.email" placeholder="请输入"></el-input>
        </el-form-item>
        
      </el-form>
      
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <br></br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="商品ID" width="150">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="商品详情" width="400" align="center">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.author" placement="top">
            <span class="text-ellipsis">{{ scope.row.author }}</span>
          </el-tooltip>
        </template>
      </el-table-column> -->


      <el-table-column label="商品主图" width="400" align="center">
        <template slot-scope="scope">
          <el-image 
            style="width: 120px; height: 100px" :src="scope.row.mainImage"
            fit="cover"
            >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="语言分类" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pageviews }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="新建时间" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.display_time }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusStyleFilter">{{ scope.row.status | statusTextFilter }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column align="center" label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="primary" size="small">编辑</el-button>

          <el-button :type="scope.row.status | buttonStyleFilter" size="small" @click="changeStatus(scope.row)">
            {{ scope.row.status | buttonFilter }}
          </el-button>
          
          <el-popover placement="top" width="160" v-model="scope.row.visible">
            <p>确定删除这一商品？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="scope.row.visible = false">确定</el-button>
            </div>
            <el-button type="danger" size="small" slot="reference" style="margin-left: 10px;">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
      
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="pagination-container"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage2"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total,sizes,prev, pager, next"
      :total="200"
    />
  </div>
</template>

<script>
import { getList } from '@/api/table'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {

  components: { quillEditor },
  filters: {
    statusStyleFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'info'
      }
      return statusMap[status] || 'danger'
    },
    statusTextFilter(status) {
      const map = {
        1: '已上架',
        2: '已下架'
      }
      return map[status] || '未知状态'
    },
    buttonFilter(status) {
      const map = {
        1: '下架',
        2: '上架'
      }
      return map[status] || '-'
    },
    buttonStyleFilter(status) {
      const map = {
        1: 'info',
        2: 'warning'
      }
      return map[status] || '-'
    }
  },
  data() {
    return {

      fileList: [],
      fileList2:[],
      visible: false,
      currentPage1: 5,
        currentPage2: 5,
        currentPage3: 5,
        currentPage4: 4,
      options: [{
          value: '选项1',
          label: '上架'
        }, {
          value: '选项2',
          label: '下架'
        }],
      value: '',
      list: [
        {index:1,
          title:'割草机',
          author:'这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情这是详情',
          mainImage:'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
          auxImage:'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          pageviews:'www.ddd.com',
          status:1,
          display_time:'2025-03-12 12:33:32',
          importance:0
        },
        {index:2,
          title:'发动机',
          author:'fesfddafafda',
          mainImage:'',
          auxImage:'',
          pageviews:'www.aaa.com',
          status:2,
          display_time:'2025-02-12 12:22:32',
          importance:0
        }
        
      ],
      listLoading: true,
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      startTime:'',
      endTime:'',
      dialogVisible: false, // 控制对话框显示
      formData: {
        langvage:'',          
        goodsName: '',
        goodsContent: '',
        link: '',
        goodsStatus:'1'
      },
      langvageList:[{value:'中文',label:'中文'},{value:'英文',label:'英文'}],
      //查询参数
      queryParams: {
        goodsName: '',
        goodsContent: '',
        goodsStatus:'1',
        startDate: '',
        endDate: ''
      },
      editorOption: {
        placeholder: '请输入文字/图片',
        theme: 'snow',  
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'indent': '-1'}, { 'indent': '+1' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'align': [] }],
            ['image']
          ]
        }
      },
      formRules: {          // 表单验证规则
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { type: 'number', message: '年龄必须为数字值', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.listLoading = true
    this.listLoading = false
  },
  methods: {
    // 查询
    handleQuery(){

    },
    // 条件重置
    handleReset(){
      this.queryParams = {
        goodsName: '',
        goodsContent: '',
        goodsStatus:'1',
        startDate: '',
        endDate: ''
      }
    },
    // 取消新增
    handleAddCancel() {
      
      this.fileList = [];
      this.formData = {          
        goodsName: '',
        goodsContent: '',
        link: '',
        goodsStatus:'1'
      };
      console.log(this.fileList);
      this.dialogVisible = false;
    },
    fetchData() {
      this.listLoading = true
      getList().then(response => {
        this.list = response.data.items
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 上下架
    changeStatus(row) {
      // api调用
      
      // 切换状态
      row.status = row.status === 1 ? 2 : 1
      this.$message.success(`已${row.status === 1 ? '上架' : '下架'}`)
    },
    // 图片
    handleRemove(file, fileList) {
        console.log(file, fileList);
        // 更新文件列表
        this.fileList = fileList;
    },
    handlePreview(file) {
      console.log(file);
      // 可以在这里实现图片预览功能
      window.open(file.url);
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功', response, file, fileList);
      this.fileList = fileList; // 关键：更新文件列表
      this.$message.success('上传成功');
    },
    handleError(err, file, fileList) {
      console.error('上传失败', err, file, fileList);
      this.$message.error('上传失败');
    },
    handleUpload(file) {
    // 创建本地URL用于预览
    const url = URL.createObjectURL(file.file);
    this.fileList.push({
      name: file.file.name,
      url: url
    });
    return false; // 阻止默认上传行为
  }
  }
}
</script>


<style scoped>
  .pagination-container {
    display: flex;
    justify-content: flex-end; 
    margin-top: 20px;
    margin-right: 30px;
  }
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f5f5;
    color: #909399;
    font-size: 30px;
  }
  .text-ellipsis {
    display: inline-block;
    width: 200px; /* 或根据实际需要设置 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>